from bs4 import BeautifulSoup
import requests
import json
import json

'''
我真是太聪明了，我去，直接拿别人破解的网站数据。我不就实现了吗，哈哈哈
网址：https://www.fangpi.net/
'''
class Fpw:

    def __init__(self):
        self.url = "https://www.fangpi.net/s/%s"
        self.play_url = "https://www.fangpi.net/api/play-url"
        self.head = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate, br, zstd',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Cookie': 'gtoken=Vz5mmkmW9uk6; gid=d62cb12f-772d-4ef1-bef5-63c44dbb4488; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1739775289; HMACCOUNT=0918E9374F8EFB4E; _ga=GA1.2.1461956199.1739775301; _gid=GA1.2.1293561616.1739775301; JSESSIONID=15k3yovymap6n1fnrptyvzjxxp; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1739781958; Hm_Iuvt_cdb524f42f23cer9b268564v7y735ewrq2324=MMCdc3jxHFRepwjmdKCMb2pjTpa2N7TT; _gat=1; _ga_ETPBRPM9ML=GS1.2.1739779361.2.1.1739782826.60.0.0',
            'Host': 'www.kuwo.cn',
            'Referer': 'https://www.kuwo.cn/search/list?key=%E6%97%A0%E5%90%8D%E7%9A%84%E4%BA%BA',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"'
        }

        self.play_head = {
            "authority": "www.fangpi.net",
            "method": "POST",
            "path": "/api/play-url",
            "scheme": "https",
            "accept": "application/json, text/javascript, */*; q=0.01",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "zh-CN,zh;q=0.9",
            "content-length": "35",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "cookie": "fp_referer=https%3A%2F%2Fwww.kuhehe.top%2F; Hm_lvt_e5a734ca1d7d50c16eb8a21a9e57ea0f=1739773470; HMACCOUNT=0918E9374F8EFB4E; Hm_lpvt_e5a734ca1d7d50c16eb8a21a9e57ea0f=1739866595",
            "origin": "https://www.fangpi.net",
            "priority": "u=1, i",
            "referer": "https://www.fangpi.net/music/11562369",
            # "sec-ch-ua": '"Google Chrome";v="131", "Chromium";v="131", "Not:A-Brand";v="24"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "x-requested-with": "XMLHttpRequest"
        }

        self.data = ["NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt", "bitrate=0", "callback=callback123", "clienttime=1629688889293"
            , "clientver=2000", "dfid=-", "inputtype=0", "iscorrection=1", "isfuzzy=0"
            , "keyword=学猫叫", "mid=1629688889293", "page=1", "pagesize=30"
            , "platform=WebFilter", "privilege_filter=0", "srcappid=2919", "tag=em", "userid=0"
            , "uuid=1629688889293", "NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt"]

        self.params = {
            'callback': 'callback123',
        }

    def handle_html(self, keyword):
        okurl = self.url % (keyword)
        response = requests.get(okurl, headers=self.head).content.decode('utf-8')
        response_html = BeautifulSoup(response, "html.parser")

        # 处理歌名与歌手名
        song_name_list = response_html.find_all(class_='col-8 col-content')

        songs = []
        for song_name in song_name_list:
            a_elem_s = song_name.find_all('a')
            # 假设每个 song_name 下只有一个 <a> 标签，或者我们只关心第一个
            if a_elem_s:
                a_elem = a_elem_s[0]  # 取第一个 <a> 标签
                song_text = song_name.get_text().replace("\n", "").replace(" ", "")
                song_href = a_elem.get('href')  # 获取 href 属性值

                song = {
                    "name": song_text,
                    "href": "https://www.fangpi.net" + song_href  # 新增 href 属性
                }

                songs.append(song)

        return str(len(songs)), songs

    def search(self, keyword):
        '''
        查询歌曲
        :param keyword: 歌名
        :return: 歌曲数据
        '''

        total, search = self.handle_html(keyword)
        pass


        list = []

        for data in search:
            list.append({
                # 歌曲名称
                "song_name": data['name'],
                # 播放地址
                "href": data["href"],
            })

        return {
            "head": None,
            "list": list,
            "total": total
        }


    def getPath(self, url, name):
        '''
        获取播放地址
        :param url: 歌曲信息地址
        :param name: 歌曲名称
        :return: 播放地址
        '''

        response = requests.request("GET", url, headers=self.head)
        text = response.text
        play_id = text[text.find("window.play_id"):text.find("window.play_id") + 100].split("\n")[0].split(" = ")[1].replace("\'", '').replace(";", '')

        # 获取歌词
        response_html = BeautifulSoup(text, "html.parser")
        song_name_list = response_html.find_all(class_='content-lrc mt-1')
        word = song_name_list[0].text
        # 获取具体的播放地址

        play_data = {
            "id": play_id
        }
        try:
            play_response = requests.post(self.play_url, headers=self.play_head, data=play_data, timeout=10)
            play_response.raise_for_status()  # 检查请求是否成功
            print("Response:", play_response.json())  # 假设响应是 JSON 格式
            print(play_response)
            loads = json.loads(play_response.text)
            return {
                # 歌曲名称
                "name": name,
                # 地址
                "mp4": loads['data']['url'],
                # 歌词
                "word": word,

            }
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return {
                    "m4a": "",
            }



if __name__ == '__main__':
    cx = Fpw()
    res = cx.search('无名的人', '1', '10')
    list = res['list']
    for e in list:
        print(e)
